package com.ee.chat.api.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ee.chat.api.common.CommonService;
import com.ee.chat.api.service.IDynamicService;
import com.ee.chat.api.service.IUserService;
import com.ee.chat.api.vo.UserAuditVO;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.service.IGeneralService;
import com.ee.chat.common.service.IPayService;
import com.ee.chat.common.service.IUpdateEntityService;
import com.ee.chat.common.service.IYieldService;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.StringUtil;
import com.ndhutu.ee.util.dwz.dw81.Dw81Util;
import com.ndhutu.ee.util.netease.im.IMUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Author Shane
 * @Date 2019/7/28 23:14
 */
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;
    @Resource
    HostMapper hostMapper;
    @Resource
    CommonService commonService;
    @Resource
    UserDynamicMapper userDynamicMapper;
    @Resource
    BaseMapper baseMapper;
    @Resource
    UserAuditLogMapper userAuditLogMapper;
    @Resource
    IGeneralService generalService;
    @Resource
    UserFocusMapper userFocusMapper;
    @Resource
    HostCallContentMapper hostCallContentMapper;
    @Resource
    HostLevelConfigMapper hostLevelConfigMapper;
    @Resource
    UserInviteLogMapper userInviteLogMapper;
    @Resource
    UserCreditLogMapper userCreditLogMapper;
    @Resource
    HostPhotosMapper hostPhotosMapper;
    @Resource
    UserConsumeLogMapper userConsumeLogMapper;
    @Resource
    UserRechargeLogMapper userRechargeLogMapper;
    @Resource
    SysConfigMapper sysConfigMapper;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    IDynamicService dynamicService;
    @Resource
    UserLableMapper userLableMapper;
    @Resource
    UserVipMapper userVipMapper;
    @Resource
    UserVipLogMapper userVipLogMapper;
    @Resource
    UserLableLibMapper userLableLibMapper;
    @Resource
    MyNeteaseApp app;
    @Resource
    IYieldService yieldService;
    @Resource
    IPayService payService;
    @Resource
    UserExpandMapper userExpandMapper;
    @Resource
    IUpdateEntityService updateEntityService;
    @Resource
    UserSetMapper userSetMapper;
    @Resource
    UserAccessLogMapper userAccessLogMapper;

    @Override
    public Result getUserInfo(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);
        Map<String, Object> user = userMapper.getUserInfo(userId);
        if(Integer.parseInt(user.get("hostAudit")+"") == 0){
            UserAuditLog userAuditLog = userAuditLogMapper.selectNewest(userId);
            if(userAuditLog != null && userAuditLog.getType() == 2){
                userAuditLog = null;
            }
            if(userAuditLog == null){
                user.put("hostAudit", -1);
            }else{
                if(userAuditLog.getType() == 0){
                    user.put("hostAudit", userAuditLog.getStatus());
                }else{
                    if(userAuditLog.getStatus() == 0){
                        user.put("hostAudit", 3);
                    }else{
                        user.put("hostAudit", -1);
                    }
                }
            }
        }
        int age = 0;
        if(user.get("birthday") != null){
            age = DateUtil.getAge((Date)(user.get("birthday")));
        }
        user.put("age", age);
        user.put("hostAuditRemind", sysConfigMapper.getValue("host_audit_remind"));

        //新增粉丝数、新增访客数
        int newAddFansNum = 0, newAddAccessNum = 0;
        Date lastBrowseFansTime = null, lastBrowseAccessTime = null;
        String key = ConstantsUtil.USER_OP + user;
        if(redisTemplate.opsForHash().get(key, "browseFansTime") != null){
            lastBrowseFansTime = DateUtil.parse(redisTemplate.opsForHash().get(key, "browseFansTime")+"");
        }
        if(redisTemplate.opsForHash().get(key, "browseAccessTime") != null){
            lastBrowseAccessTime = DateUtil.parse(redisTemplate.opsForHash().get(key, "browseAccessTime")+"");
        }
        newAddFansNum = userFocusMapper.getUserNum(userId, 1, lastBrowseFansTime);
        newAddAccessNum = userAccessLogMapper.getUserNum(userId, lastBrowseAccessTime);
        user.put("newAddFansNum", newAddFansNum);
        user.put("newAddAccessNum", newAddAccessNum);
        data.put("user", user);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getUserAccessLogs(String token, Integer type, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = baseMapper.getUserAccessLogs(p, userId, type);
        List<Map<String, Object>> accessLogs = iPage.getRecords();

        data.put("accessLogs", accessLogs);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getUserDynaimcs(String token, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userDynamicMapper.getUserDynamics(p, userId);
        List<Map<String, Object>> dynamics = iPage.getRecords();

        dynamicService.handleDynamic(dynamics);

        data.put("dynamics", dynamics);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getUserFriends(String token, Integer toUserId, Integer type, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userMapper.getUserFriends(p, userId, toUserId == null ? userId : toUserId, type);
        List<Map<String, Object>> friends =iPage.getRecords();

        data.put("friends", friends);
        return Result.returnSuccess(data);
    }

    @Override
    public Result setDND(String token, Integer dnd) throws Exception {
        Integer userId = commonService.getUserId(token);

        //更新勿扰模式
        UserSet userSet = new UserSet(userId);
        userSet.setDnd(dnd);
        updateEntityService.updateUserSet(userSet);

        //更新用户状态
        User user = new User(userId);
        if(dnd == 1){  //在线且开启勿扰
            user.setOnline(1);
        }else{
            user.setOnline(3);
        }
        userMapper.updateById(user);

        return Result.returnSuccess(null);
    }

    @Override
    public Result getAuditInfo(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Integer userId = commonService.getUserId(token);
        Map<String, Object> auditInfo = new HashMap<>();

        UserAuditLog userAuditLog = userAuditLogMapper.selectNewest(userId);
        User user = userMapper.selectById(userId);

        if(userAuditLog == null || userAuditLog.getStatus() == 2 || userAuditLog.getStatus() == 3){
            userAuditLog = new UserAuditLog();
        }
        auditInfo.put("video", userAuditLog.getVideo());
        List<Map<String, Object>> photos = new ArrayList<>();
        if(userAuditLog.getPotos() == null || userAuditLog.getStatus() != 0){
            List<HostPhotos> hostPhotos = hostPhotosMapper.selectByUserId(userId);
            for(HostPhotos hostPhoto : hostPhotos){
                Map<String, Object> photo = new HashMap<>();
                photo.put("icon", hostPhoto.getIcon());
                photo.put("isFirst", hostPhoto.getOrderId());
                photos.add(photo);
            }
        }
        auditInfo.put("potos", userAuditLog.getPotos() == null ? photos : (userAuditLog.getStatus() == 0 ? JSONArray.parseArray(userAuditLog.getPotos(), Map.class) : photos));
//        auditInfo.put("potos", userAuditLog.getPotos() == null ? photos : JSONArray.parseArray(userAuditLog.getPotos(), Map.class));
        auditInfo.put("icon", userAuditLog.getIcon() == null ? user.getIcon() : userAuditLog.getIcon());
        auditInfo.put("name", userAuditLog.getName() == null ? user.getName() : userAuditLog.getName());
        auditInfo.put("birthday", user.getBirthday() == null ? null : DateUtil.format(user.getBirthday(), DateUtil.pattern_day));
        auditInfo.put("gender", user.getGender());
        auditInfo.put("phone", user.getPhone());
        auditInfo.put("height", user.getHeight());
        auditInfo.put("weight", user.getWeight());
        auditInfo.put("persionSign", userAuditLog.getPersionSign() == null ? user.getPersionSign() : userAuditLog.getPersionSign());
        auditInfo.put("idCardFront", userAuditLog.getIdCardFront());
        auditInfo.put("idCardFeverse", userAuditLog.getIdCardReverse());
        auditInfo.put("handIdCard", userAuditLog.getHandIdCard());

        Map<String, Object> uss = null, city = null, pro = null, em = null;
        List<Map<String, Object>> lables;
        if(user.getUssId() != null){
            uss = userAuditLogMapper.getUSSById(user.getUssId());
        }
        if(user.getCityCode() != null){
            city = userAuditLogMapper.getAreaByCode(Integer.parseInt(user.getCityCode()));
        }
        if(user.getProId() != null){
            pro = userAuditLogMapper.getProById(user.getProId());
        }
        if(user.getEmId() != null){
            em = userAuditLogMapper.getEmById(user.getEmId());
        }
        lables = userLableMapper.getUserLables(userId);
        auditInfo.put("uss", uss);
        auditInfo.put("city", city);
        auditInfo.put("pro", pro);
        auditInfo.put("em", em);
        auditInfo.put("lables", lables);
        auditInfo.put("persionVideo", userAuditLog.getPersionVideo());
        auditInfo.put("wxNo", userAuditLog.getWxNo());

        data.put("auditInfo", auditInfo);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getAreaLib(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        String json = redisTemplate.opsForHash().get("data", "areaLibToCity")+"";
        List<Map<String, Object>> areaLibToCity = (List<Map<String, Object>>)JSONArray.parse(json);
        data.put("areaLibToCity", areaLibToCity);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getLableLib(String token, Integer host) throws Exception {
        Integer userId = commonService.getUserId(token);

        Map<String, Object> data = new HashMap<>();
        List<Map<String, Object>> lableLib = userLableLibMapper.getUserLableLib();
        data.put("lableLib", lableLib);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getUSSLib(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        List<Map<String, Object>> uusLib = baseMapper.getUSSLib();
        data.put("uusLib", uusLib);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getProLib(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        List<Map<String, Object>> proLib = baseMapper.getProLib();
        data.put("proLib", proLib);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getEmLib(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        List<Map<String, Object>> emLib = baseMapper.getEmLib();
        data.put("emLib", emLib);

        return Result.returnSuccess(data);
    }

    @Override
    public Result saveAuditInfo(UserAuditVO vo) throws Exception {
        Map<String, Object> data = new HashMap<>();

        int userId = commonService.getUserId(vo.getToken());
        User user = userMapper.selectById(userId);

        if(user.getGender() != null && !user.getGender().equals(vo.getGender())){
            return Result.returnFailure("性别不能修改");
        }
        if(user.getPhone() != null && vo.getPhone() == null){
            return Result.returnFailure("手机号不能删除");
        }
        if((user.getPhone() == null && !StringUtil.isEmpty(vo.getPhone())) || (user.getPhone() != null && !user.getPhone().equals(vo.getPhone()))){
            String key = "code:"+vo.getPhone()+":bind";
            String value = redisTemplate.boundHashOps(key).get("code")+"";
            if(StringUtil.isEmpty(vo.getCode()) || !vo.getCode().equals(value)){
                return Result.returnFailure("验证码错误");
            }
        }

        UserAuditLog userAuditLog = userAuditLogMapper.selectNewest(userId);
        if(userAuditLog != null && userAuditLog.getStatus() == 0){
            if(userAuditLog.getType() == 0){
                return Result.returnFailure("认证资料审核中，不能进行操作");
            }else if(userAuditLog.getType() == 1){
                return Result.returnFailure("资料更新审核中，不能进行操作");
            }/*else{
                return Result.returnFailure("基本信息审核中，不能进行操作");
            }*/
        }

        //男性用户不能认证主播
        if(vo.getType() == 0 && ((user.getGender() != null && user.getGender() == 1) || vo.getGender() == 1)){
            return Result.returnFailure("男性用户不能进行真人认证");
        }

        UserSet userSet = userSetMapper.selectByUserId(userId);
        if(vo.getType() == 0 && userSet != null && userSet.getAudit() == 1){
            return Result.returnFailure("你已多次认证被驳回，现已无法认证为主播，详情请咨询客服");
        }

        //登录成功立马进行真人认证的用户，其注册资料审核作废，真人认证信息进行覆盖
        if(userAuditLog != null && userAuditLog.getType() == 2){
            userAuditLogMapper.deleteById(userAuditLog);
        }

        userAuditLog = new UserAuditLog();
        userAuditLog.setType(vo.getType());
        userAuditLog.setUserId(userId);
        //认证
        if(vo.getType() == 0){
            userAuditLog.setVideo(vo.getVideo());
            userAuditLog.setPotos(vo.getPotos());
            userAuditLog.setName(vo.getName());
            userAuditLog.setBirthday(vo.getBirthday());
            userAuditLog.setGender(vo.getGender());
            userAuditLog.setPhone(vo.getPhone());
            userAuditLog.setHeight(vo.getHeight());
            userAuditLog.setWeight(vo.getWeight());
            userAuditLog.setUssId(vo.getUssId());
            userAuditLog.setCityCode(vo.getCityCode());
            userAuditLog.setProId(vo.getProId());
            userAuditLog.setEmId(vo.getEmId());
            userAuditLog.setLables(vo.getLables());
            userAuditLog.setPersionSign(vo.getPersionSign());
            userAuditLog.setIdCardFront(vo.getIdCardFront());
            userAuditLog.setIdCardReverse(vo.getIdCardReverse());
            userAuditLog.setHandIdCard(vo.getHandIdCard());
            userAuditLogMapper.insert(userAuditLog);
        }else{
            boolean inviteRateFlag = false;
            if(StringUtil.isEmpty(user.getGender()) && "1".equals(vo.getGender())){
                inviteRateFlag = true;
            }

            user.setBirthday(vo.getBirthday());
            user.setGender(vo.getGender());
            user.setPhone(vo.getPhone());
            user.setHeight(vo.getHeight());
            user.setWeight(vo.getWeight());
            user.setUssId(vo.getUssId());
            user.setCityCode(vo.getCityCode());
            user.setProId(vo.getProId());
            user.setEmId(vo.getEmId());
            userMapper.updateById(user);

            //指定时间之后注册的新用户绑定男性性别，获取邀请奖励
            String dateStr = "2020-07-13 00:00:00";
            Date date = DateUtil.parse(dateStr, DateUtil.pattern_general);
            if(inviteRateFlag && user.getCreateTime().getTime() - date.getTime() > 0){
                yieldService.handleInviteRegYield(userId);
            }

            //更新IM

            IMUtil.updateUinfo(app.getIdPrefix()+userId, null, null, vo.getGender(), app);

            //标签更新
            List<Integer> lableIds = JSONArray.parseArray(vo.getLables(), Integer.class);
            userLableMapper.deleteByUserId(userId);
            for(Integer lableId : lableIds){
                UserLable userLable = new UserLable(userId, lableId);
                userLableMapper.insert(userLable);
            }

            //需审核的修改项
            boolean flag = false;
            if(!StringUtil.isEmpty(vo.getPotos()) && !"[]".equals(vo.getPotos())){
                List<Map> newPhotos = JSONArray.parseArray(vo.getPotos(), Map.class);
                List<HostPhotos> orgPotos = hostPhotosMapper.selectByUserId(userId);
                for(Map map : newPhotos){
                    boolean photoFlag = false;
                    for(HostPhotos potos : orgPotos){
                        if(potos.getIcon().equals(map.get("icon")) && potos.getOrderId().equals(map.get("isFirst"))){
                            photoFlag = true;
                            break;
                        }
                    }
                    if(!photoFlag){
                        flag = true;
                        userAuditLog.setPotos(vo.getPotos());
                        break;
                    }
                }

                if(!flag && newPhotos.size() < orgPotos.size()){    //存在删除照片
                    for(HostPhotos potos : orgPotos){
                        boolean f = false;
                        for(Map map : newPhotos){
                            if(potos.getIcon().equals(map.get("icon"))){
                                f = true;
                                break;
                            }
                        }
                        if(!f){
                            hostPhotosMapper.deleteById(potos.getId());
                        }
                    }
                }
            }

            if(!user.getIcon().equals(vo.getIcon())){
                userAuditLog.setIcon(vo.getIcon());
                flag = true;
            }
            if(!user.getName().equals(vo.getName())){
                userAuditLog.setName(vo.getName());
                flag = true;
            }
            if(!vo.getPersionSign().equals(user.getPersionSign())){
                userAuditLog.setPersionSign(vo.getPersionSign());
                flag = true;
            }
            if(flag){
                userAuditLogMapper.insert(userAuditLog);
            }
        }

        data.put("hostAuditRemind", sysConfigMapper.getValue("host_audit_remind"));

        return Result.returnSuccess(null);
    }

    /**
     * 处理需要更换的图片
     * @Author Shane
     * @Date 2020/4/21 12:11
     * @param
     * @param freshs
     * @return
     */
    private List<Map<String, Object>> handlePotos(Integer userId, List<Map> freshs){
        List<HostPhotos> olds = hostPhotosMapper.selectByUserId(userId);

        //获取需要新增数数据
        List<Map<String, Object>> adds = new ArrayList<>();
        for(Map<String, Object> fresh : freshs){
            boolean flag = false;
            for(HostPhotos old : olds){
                Integer isFirst = Integer.parseInt(fresh.get("isFirst")+"");
                if(isFirst.equals(1)){
                    if(old.getOrderId().equals(1) && old.getIcon().equals(fresh.get("icon"))){
                        flag = true;
                        continue;
                    }
                }else{
                    if(old.getIcon().equals(fresh.get("icon"))){
                        flag = true;
                        continue;
                    }
                }
            }
            if(!flag){
                adds.add(fresh);
            }
        }

        //获取需要删除的数据
        List<HostPhotos> dels = new ArrayList<>();
        for(HostPhotos old : olds){
            boolean flag = false;
            for(Map<String, Object> fresh : freshs){
                if(old.getIcon().equals(fresh.get("icon"))){
                    flag = true;
                    continue;
                }
            }
            if(!flag){
                dels.add(old);
            }
        }

        //操作（当前需要全部更换图片时，不执行该操作）
        if(dels.size() < olds.size()){
            for(HostPhotos del : dels){
                hostPhotosMapper.deleteById(del.getId());
            }
        }

        return adds;
    }

    @Override
    public Result focus(String token, Integer toUserId, Integer type) throws Exception {
        Integer userId = commonService.getUserId(token);

        Host host = hostMapper.selectByUserId(userId);
        Host toHost = hostMapper.selectByUserId(toUserId);
        if(host == null && toHost == null){
            return Result.returnFailure("用户与用户之间不能相互关注");
        }
        if(host != null && toHost != null){
            return Result.returnFailure("主播与主播之间不能相关关注");
        }

        if(type == 0){
            userFocusMapper.cancelFocus(toUserId, userId);
        }else if(type == 1){
            UserFocus focus = new UserFocus(toUserId, userId);
            userFocusMapper.insert(focus);
        }

        return Result.returnSuccess(null);
    }

    /**
     * 添加招呼内容
     * @Author Shane
     * @Date 2019/10/6 23:52
     * @param
     * @return
     */
    @Override
    public Result addCallContent(String token, String content) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Integer userId = commonService.getUserId(token);

        int count = hostCallContentMapper.getByUserIdAndContentCount(userId, content);
        if(count > 1){
            return Result.returnFailure("列表中或待审核已有该招呼，不能重复添加");
        }

        HostCallContent first = hostCallContentMapper.selectFirstHostCallCentent(userId, 0);
        HostCallContent hostCallContent = new HostCallContent(userId, content, first.getOrderId() + 1);
        hostCallContentMapper.insert(hostCallContent);

        data.put("callContent", hostCallContent);
        return Result.returnSuccess(data);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveCallContent(String token, String contents) throws Exception {

        List<Map>  contentList = JSONArray.parseArray(contents, Map.class);
        for(Map<String, Object> content : contentList){
            HostCallContent hostCallContent = new HostCallContent();
            hostCallContent.setId(Integer.parseInt(content.get("id")+""));
            hostCallContent.setOrderId(Integer.parseInt(content.get("orderId")+""));

            hostCallContentMapper.updateById(hostCallContent);
        }

        return Result.returnSuccess(null);
    }

    /**
     * 删除招呼内容
     * @Author Shane
     * @Date 2019/10/6 23:53
     * @param
     * @return
     */
    @Override
    public Result delCallContent(String token, String ids) throws Exception {
        Integer userId = commonService.getUserId(token);
        String[] idArr = ids.split(",");

        //至少保留一条已经审核通过的招呼
        int count = idArr.length;
        for(String id : idArr){
            HostCallContent hostCallContent = hostCallContentMapper.selectById(id);
            if(hostCallContent.getStatus() == 0){
                count --;
            }
        }
        int num = hostCallContentMapper.getUserCallContentNum(userId);
        if(count >= num){
            return Result.returnFailure("至少保留一条已审核通过的招呼");
        }

        List<Integer> idList = new ArrayList<>();
        for(String id : idArr){
            HostCallContent hostCallContent = hostCallContentMapper.selectById(id);
            if(hostCallContent.getUserId() == 0){
                return Result.returnFailure("内置招呼不能删除");
            }
            idList.add(Integer.parseInt(id));
        }

        hostCallContentMapper.deleteBatchIds(idList);

        return Result.returnSuccess(null);
    }

    /**
     * 获取通话价格
     * @Author Shane
     * @Date 2019/11/13 16:10
     * @param
     * @return
     **/
    @Override
    public Result getCharge(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Integer userId = commonService.getUserId(token);
        Host host = hostMapper.selectByUserId(userId);

        List<Map<String, Object>> charges = hostLevelConfigMapper.getCharges(host.getLevel());
        data.put("charges",charges);

        return Result.returnSuccess(data);
    }

    /**
     * 设置通话价格
     * @Author Shane
     * @Date 2019/11/13 16:10
     * @param
     * @return
     **/
    @Override
    public Result setCharge(String token, Integer chargeId) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Integer userId = commonService.getUserId(token);

        Host host = hostMapper.selectByUserId(userId);
        if(host == null){
            return Result.returnFailure("非主播用户不能设置通话价格");
        }

        HostLevelConfig hostLevelConfig = hostLevelConfigMapper.selectById(chargeId);
        if(hostLevelConfig == null){
            return  Result.returnFailure("价格不存在");
        }
        host.setChargeId(chargeId);
        hostMapper.updateById(host);

        data.put("charge", hostLevelConfig.getCharge());
        data.put("earn", hostLevelConfig.getEarn());

        return Result.returnSuccess(data);
    }

    @Override
    public Result getInviteInfo(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        int inviteCount = userInviteLogMapper.getInviteUserCount(userId);
        double inviteCredit = new BigDecimal(userCreditLogMapper.getInviteCreditCount(userId)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        List<Map<String, Object>> dequity = (List<Map<String, Object>>)(JSONArray.parse(sysConfigMapper.getValue("invite_award_dequity")));

        Map<String, Object> invite = new HashMap<>();
        invite.put("inviteCount", inviteCount);
        invite.put("inviteCredit", inviteCredit);
        invite.put("dequity", dequity);

        User user = userMapper.selectById(userId);
        invite.put("name", user.getName());
        invite.put("icon", user.getIcon());

        data.put("invite", invite);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getInviteUser(String token, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userInviteLogMapper.getUserInviteUser(p, userId);
        List<Map<String, Object>> users = iPage.getRecords();

        data.put("users", users);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getInviteAward(String token, Integer page, Integer limit) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);

        Page<Map<String, Object>> p = new Page<>(page, limit);
        IPage<Map<String, Object>> iPage = userCreditLogMapper.getInviteChargeLog(p, userId);
        List<Map<String, Object>> awards = iPage.getRecords();
        Iterator<Map<String, Object>> it = awards.iterator();

        while (it.hasNext()){
            Map<String, Object> award = it.next();
            int type = Integer.parseInt(award.get("type")+"");
            int type2 = Integer.parseInt(award.get("type2")+"");
            int consumId = Integer.parseInt(award.get("consumId")+"");

            Integer toUserId;
            String toName, toIcon;
            String desc = null;
            User toUser = null;
            if(type == 1 || type == 9){
                UserRechargeLog userRechargeLog = userRechargeLogMapper.selectById(consumId);
                toUser = userMapper.selectById(userRechargeLog.getUserId());
                if(type == 1){
                    desc = "直接邀请的用户"+toUser.getName()+"充值获得提成积分";
                }else if(type == 9){
                    desc = "间接邀请的用户"+toUser.getName()+"充值获得提成积分";
                }

            }else if(type == 6 || type == 7){
                UserConsumeLog userConsumeLog = userConsumeLogMapper.selectById(consumId);
                toUser = userMapper.selectById(userConsumeLog.getToUserId());

                if(type2 == 0){
                    if(type == 6){
                        desc = "获取邀请的"+toUser.getName()+"主播视频通话积分的提成";
                    }else if(type == 7){
                        desc = "获取间接邀请的"+toUser.getName()+"主播视频通话的积分的二级提成";
                    }
                }else if(type2 == 1){
                    if(type == 6){
                        desc = "获取邀请的"+toUser.getName()+"主播动态被解锁积分的提成";
                    }else if(type == 7){
                        desc = "获取间接邀请的"+toUser.getName()+"主播动态被解锁积分的二级提成";
                    }
                }else if(type2 == 2){
                    if(type == 6){
                        desc = "获取邀请的"+toUser.getName()+"主播聊天积分的提成";
                    }else if(type == 7){
                        desc = "获取间接邀请的"+toUser.getName()+"主播聊天积分的二级提成";
                    }
                }else if(type2 == 3 || type2 == 4 || type2 == 5 || type2 == 6){
                    if(type == 6){
                        desc = "获取邀请的"+toUser.getName()+"主播收到礼物积分的提成";
                    }else if(type == 7){
                        desc = "获取间接邀请的"+toUser.getName()+"主播收到礼物积分的二级提成";
                    }
                }else{
                    desc = "其他";
                }
            }else if(type == 8){
                UserAuditLog userAuditLog = userAuditLogMapper.selectById(consumId);
                toUser = userMapper.selectById(userAuditLog.getUserId());
                desc = "直接邀请的用户"+toUser.getName()+"认证成功获得提成积分";
            }else if(type == 10){
                UserVipLog userVipLog =userVipLogMapper.selectById(consumId);
                toUser = userMapper.selectById(userVipLog.getUserId());
                desc = "直接邀请的用户"+toUser.getName()+"购买会员获得提成积分";
            }else if(type == 11){
                toUser = userMapper.selectById(consumId);
                desc = "直接邀请用户"+toUser.getName()+"注册获取奖励积分";
            }
            toUserId = toUser.getId();
            toName = toUser.getName();
            toIcon = toUser.getIcon();

            award.put("userId", toUserId);
            award.put("name", toName);
            award.put("icon", toIcon);
            award.put("gender", toUser.getGender() == null ? -1 : toUser.getGender());
            award.remove("type2");
            award.put("desc", desc);
        }

        double inviteCredit = new BigDecimal(userCreditLogMapper.getInviteCreditCount(userId)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //兼容版本
        int v = generalService.versionCompare(token, "1.1.5", "10.10.13");
        if(v <= 0){
            inviteCredit = (int) inviteCredit;
        }

        data.put("awards", awards);
        data.put("inviteCredit", inviteCredit);
        return Result.returnSuccess(data);
    }

    @Override
    public Result getCellUserInfo(String token, Integer toUserId) throws Exception {
        Map<String, Object> data = new HashMap<>();

        Integer userId = commonService.getUserId(token);
        Map<String, Object> user = new HashMap<>();

        Map<String, Object> userInfo = userMapper.getCellUserInfo(toUserId);
        Host host = hostMapper.selectByUserId(userId);
        if(host == null){
            host = hostMapper.selectByUserId(toUserId);
        }
        HostLevelConfig hostLevelConfig = hostLevelConfigMapper.selectById(host.getChargeId());
        userInfo.put("charge", hostLevelConfig.getCharge());
        userInfo.put("earn", hostLevelConfig.getEarn());
        List<Map<String, Object>> lables = userLableMapper.getUserLables(toUserId);
        userInfo.put("lables", lables);
        data.put("userInfo", userInfo);

        user.put("host", host == null ? 0 : 1);
        data.put("user", user);

        return Result.returnSuccess(data);
    }

    @Override
    public Result setPrivacy(String token, Integer privacy) throws Exception {
        Integer userId = commonService.getUserId(token);

        UserVip userVip = userVipMapper.selectValidVip(userId);
        if(userVip == null){
            return Result.returnFailure("会员用户才能设置该功能");
        }else{
            UserSet userSet = new UserSet(userId);
            userSet.setPrivacy(privacy);
            updateEntityService.updateUserSet(userSet);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("privacy", privacy);

        return Result.returnSuccess(data);
    }

    @Override
    public Result setLocal(String token, Integer local) throws Exception {
        Integer userId = commonService.getUserId(token);

        Host host = hostMapper.selectByUserId(userId);
        if(host == null){
            return Result.returnFailure("主播用户才可设置同城状态");
        }else{
            UserSet userSet = new UserSet(userId);
            userSet.setLocal(local);
            updateEntityService.updateUserSet(userSet);
        }

        Map<String, Object> data = new HashMap<>();
        data.put("local", local);

        return Result.returnSuccess(data);
    }

    @Override
    public Result getInviteUrl(String token) throws Exception {
        Map<String, Object> data = new HashMap<>();
        Integer userId = commonService.getUserId(token);

        Integer inviteShortUrl = Integer.parseInt(sysConfigMapper.getValue("invite_short_url"));
        String inviteUrl, longUrl;
        if(inviteShortUrl == 0){    //不使用短链
            User user = userMapper.selectById(userId);
            longUrl = sysConfigMapper.getValue("share_domain")+"/invite/index.html?inviteCode="+user.getInviteCode();
            inviteUrl = longUrl;

        }else { //使用短链
            UserExpand userExpand = userExpandMapper.selectByUserId(userId);
            //已存在短链
            if(userExpand != null && !StringUtil.isEmpty(userExpand.getInviteUrl())){
                inviteUrl = userExpand.getInviteUrl();

            }else{
                User user = userMapper.selectById(userId);
                longUrl = sysConfigMapper.getValue("share_domain")+"/invite/index.html?inviteCode="+user.getInviteCode();
                //不存在短链，重新生成
                inviteUrl = Dw81Util.createShortUrl(longUrl);

                if(userExpand == null){
                    userExpand = new UserExpand(userId);
                }
                userExpand.setInviteUrl(inviteUrl);
                if(userExpand.getId() == null){
                    userExpandMapper.insert(userExpand);
                }else{
                    userExpandMapper.updateById(userExpand);
                }
            }
        }

        data.put("inviteUrl", inviteUrl);

        return Result.returnSuccess(data);
    }
}
